import {defineStore} from "pinia";
import {Message} from "@arco-design/web-vue";
import {downloadFile} from "@/services/uploadApi.ts";

type State = {
    download: {
        // 下载的文件标识
        fileId: string,
        // 下载的总大小
        totalSize: number,
        // 已经下载的字节
        downloadedBytes: number
        // 存储的分块
        chunks: Blob[]
        // 下载的文件名称
        fileName: string
    },
    // 分片大小
    chunkSize: number,
    // 是否暂停
    isPaused: boolean,
    // 下载状态
    isDownloading: boolean
    // 下载进度
    downloadProgress: number
}

const useLargeFileStore = defineStore('largeFile', {
    state: (): State => ({
        download: {
            fileId: '',
            totalSize: 0,
            downloadedBytes: 0,
            chunks: [],
            fileName: ''
        },
        chunkSize: 2 * 1024 * 1024,
        isPaused: false,
        isDownloading: false,
        downloadProgress: 0
    }),

    actions: {
        // 开始下载
        async startDownload(fileId: string, totalSize: number, fileName: string, fn: Function) {
            // if (this.isDownloading) {
            //     Message.warning('文件下载中')
            //     return
            // }
            this.isDownloading = true
            this.isPaused = false
            this.download.fileId = fileId;
            this.download.totalSize = totalSize;
            this.download.fileName = fileName;
            this.download.chunks = []
            this.download.downloadedBytes = 0;
            this.downloadProgress = 0
            try {
                await this.chunkDownload(fn)
            }
            catch (error) {
            }
        },

        // 分片下载
        async chunkDownload(fn: Function) {
            const {fileId, totalSize, downloadedBytes} = this.download
            const totalChunks = Math.ceil(totalSize / this.chunkSize); // 计算总分片数

            for (let i = Math.floor(downloadedBytes / this.chunkSize); i < totalChunks; i++) {
                if (this.isPaused) {

                    break; // 退出循环，暂停下载
                }
                const start = i * this.chunkSize
                const end = Math.min(start + this.chunkSize, totalSize) - 1
                // 分块下载
                const res = await downloadFile({fileId}, {start, end, total: totalSize})

                this.download.chunks.push(res)

                this.download.downloadedBytes = end + 1;

                // 更新进度
                this.downloadProgress = Math.floor((this.download.downloadedBytes / totalSize) * 100)
                // console.log(`下载中：${this.downloadProgress}%`);
            }

            // 下载完成后合并
            if (this.download.downloadedBytes === totalSize) {
                this.isDownloading = false;
                const completeFile = new Blob(this.download.chunks);
                const downloadUrl = URL.createObjectURL(completeFile);
                const link = document.createElement("a");
                link.href = downloadUrl;
                link.download = this.download.fileName; // 指定下载的文件名
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                fn()
                // console.log("文件下载完成");
            }
        },

        // 暂停
        pauseDownload() {
            if (!this.isDownloading) {
                Message.warning("下载未开始");
                return;
            }
            this.isPaused = true;
            Message.info('下载已暂停')
        },
        // 恢复
        async resumeDownload(fn: Function) {
            if (!this.isPaused) {
                Message.warning("下载未暂停或已经完成");
                return;
            }
            this.isPaused = false;
            Message.info('下载已恢复')
            await this.chunkDownload(fn)
        },
        getDownloadData() {
            return this.download
        },
        getDownloadProgress() {
            return this.downloadProgress
        }
    }
})

export default useLargeFileStore;